﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using MyPlanSilverlight.Utils;
using MyPlanSilverlight.Models;

namespace MyPlanSilverlight
{
    public partial class CompanyList : UserControl
    {
        public CompanyList()
        {
            InitializeComponent();
            FetchCompanys();
        }

        private List<Company> companyList;

        private void FetchCompanys()
        {
            string url = App.Current.Host.Source.ToString();
            //url = url.Substring(0, url.IndexOf('/', 7) + 1) + "api/company/findByPage?page={0}&limit={1}";
            //url = string.Format(url, 0, 10);

            url = url.Substring(0, url.IndexOf('/', 7) + 1) + "api/company/findByPage";

            HttpHelper helper = new HttpHelper();
            helper.Get(url, 
                new KeyValuePair<string, string>("page", Convert.ToString(0)),
                new KeyValuePair<string, string>("limit", Convert.ToString(10)));

            helper.ResponseComplete += new HttpResponseCompleteEventHandler(this.CommandComplete);
        }

        private void CommandComplete(HttpResponseCompleteEventArgs e)
        {
            this.Dispatcher.BeginInvoke(() =>
            {
                Response response = Response.Init(e.Response);

                if (response.Status == ConstanCodes.SUCCESS)
                {
                    this.companyList = response.toEntityList<Company>();
                    BindDataList();
                }
                else if (response.Status == ConstanCodes.SERVER_ERROR)
                {
                    MessageBox.Show("服务器错误");
                }
            });
        }

        private void BindDataList()
        {
            this.dataGrid.ItemsSource = this.companyList;
        }
    }
}
